<template>
  <div class="comment-list">
    <a-page-header
      title="评论管理"
      sub-title="管理系统中的评论，包括编辑、删除和审核等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="评论内容">
          <a-input v-model:value="searchForm.content" placeholder="请输入评论内容" allowClear />
        </a-form-item>
        <a-form-item label="作品名称">
          <a-input v-model:value="searchForm.artworkName" placeholder="请输入作品名称" allowClear />
        </a-form-item>
        <a-form-item label="用户名称">
          <a-input v-model:value="searchForm.username" placeholder="请输入用户名称" allowClear />
        </a-form-item>
        <a-form-item label="审核状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择审核状态"
            allowClear
            style="width: 150px"
          >
            <a-select-option :value="0">待审核</a-select-option>
            <a-select-option :value="1">已通过</a-select-option>
            <a-select-option :value="2">已拒绝</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><reload-outlined /></template>重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="commentList" 
        :loading="tableLoading" 
        :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="showEditModal(record)" v-permission="'content:comment:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-button type="primary" @click="showReviewModal(record)" v-permission="'content:comment:review'">
                  <template #icon><check-outlined /></template>审核
                </a-button>
                <a-popconfirm
                title="确定要删除这条评论吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'content:comment:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
            </a-tag>
            </template>
            <template v-else-if="column.key === 'content'">
              <div class="comment-content-cell">{{ record.content }}</div>
            </template>
        </template>
    </a-table>

    <!-- 编辑评论弹窗 -->
    <a-modal
      title="编辑评论"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="评论内容" name="content">
          <a-textarea v-model:value="formState.content" placeholder="请输入评论内容" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 审核评论弹窗 -->
    <a-modal
      title="审核评论"
      :visible="reviewModalVisible"
      @ok="handleReviewModalOk"
      @cancel="handleReviewModalCancel"
      :confirmLoading="reviewModalLoading"
    >
      <a-form
        ref="reviewFormRef"
        :model="reviewFormState"
        :rules="reviewRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="审核结果" name="status">
          <a-radio-group v-model:value="reviewFormState.status">
            <a-radio :value="1">通过</a-radio>
            <a-radio :value="2">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="审核意见" name="remark" v-if="reviewFormState.status === 2">
          <a-textarea v-model:value="reviewFormState.remark" placeholder="请输入拒绝原因" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, CheckOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

export default defineComponent({
  name: 'CommentList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    EditOutlined,
    DeleteOutlined,
    CheckOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const tableLoading = ref(false);
    const commentList = ref([]);
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });

    const searchForm = reactive({
      content: '',
      artworkName: '',
      username: '',
      status: undefined,
    });

    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '评论内容',
        dataIndex: 'content',
        key: 'content',
        ellipsis: true,
        width: 300,
      },
      {
        title: '作品名称',
        dataIndex: 'artworkName',
        key: 'artworkName',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '用户昵称',
        dataIndex: 'username',
        key: 'username',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '点赞数',
        dataIndex: 'likeCount',
        key: 'likeCount',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '操作',
        key: 'action',
        width: 250,
      }
    ];

    // 获取评论列表
    const fetchCommentList = (page = pagination.current, pageSize = pagination.pageSize) => {
      tableLoading.value = true;
      const params = {
        current: page,
        size: pageSize,
        ...searchForm
      };
      
      axios.get('/api/comment/page', { params })
        .then(response => {
          if (response.data.code === 200) {
            commentList.value = response.data.data.records;
            pagination.total = response.data.data.total;
            pagination.current = page;
            pagination.pageSize = pageSize;
          } else {
            message.error(response.data.message || '获取评论列表失败');
          }
        })
        .catch(error => {
          console.error('获取评论列表失败:', error);
          message.error('获取评论列表失败');
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 表格变化事件
    const handleTableChange = (pag) => {
      fetchCommentList(pag.current, pag.pageSize);
    };

    // 搜索按钮点击事件
    const handleSearch = () => {
      // 搜索时重置到第一页
      fetchCommentList(1, pagination.pageSize);
    };
    
    // 重置搜索条件
    const resetSearch = () => {
      searchForm.content = '';
      searchForm.artworkName = '';
      searchForm.username = '';
      searchForm.status = undefined;
      fetchCommentList(1, pagination.pageSize);
    };

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '待审核';
        case 1: return '已通过';
        case 2: return '已拒绝';
        default: return '未知';
      }
    };

    // 获取状态颜色
    const getStatusColor = (status) => {
      switch (status) {
        case 0: return 'orange';
        case 1: return 'green';
        case 2: return 'red';
        default: return 'default';
      }
    };

    // 编辑弹窗相关
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const formRef = ref(null);
    const formState = reactive({
      id: null,
      content: '',
    });

    const rules = {
      content: [
        { required: true, message: '请输入评论内容', trigger: 'blur' },
        { max: 500, message: '评论内容不能超过500个字符', trigger: 'blur' }
      ],
    };

    // 显示编辑弹窗
    const showEditModal = (record) => {
      formState.id = record.id;
      formState.content = record.content;
      modalVisible.value = true;
    };

    // 弹窗确认
    const handleModalOk = () => {
      formRef.value.validate().then(() => {
        modalLoading.value = true;
        
        axios.put(`/api/comment/${formState.id}`, formState)
          .then(response => {
            if (response.data.code === 200) {
              message.success('编辑成功');
              modalVisible.value = false;
              fetchCommentList();
            } else {
              message.error(response.data.message || '编辑失败');
            }
          })
          .catch(error => {
            console.error('编辑失败:', error);
            message.error('编辑失败');
          })
          .finally(() => {
            modalLoading.value = false;
          });
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    // 弹窗取消
    const handleModalCancel = () => {
      modalVisible.value = false;
    };

    // 删除评论
    const handleDelete = (id) => {
      axios.delete(`/api/comment/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            message.success('删除成功');
            fetchCommentList();
          } else {
            message.error(response.data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除失败:', error);
          message.error('删除失败');
        });
    };

    // 审核弹窗相关
    const reviewModalVisible = ref(false);
    const reviewModalLoading = ref(false);
    const reviewFormRef = ref(null);
    const reviewFormState = reactive({
      id: null,
      status: 1,
      remark: '',
    });

    const reviewRules = {
      status: [
        { required: true, message: '请选择审核结果', trigger: 'change' }
      ],
      remark: [
        { required: true, message: '请输入拒绝原因', trigger: 'blur', validator: (rule, value) => {
          if (reviewFormState.status === 2 && (!value || value.trim() === '')) {
            return Promise.reject('请输入拒绝原因');
          }
          return Promise.resolve();
        }}
      ],
    };

    // 显示审核弹窗
    const showReviewModal = (record) => {
      reviewFormState.id = record.id;
      reviewFormState.status = 1;
      reviewFormState.remark = '';
      reviewModalVisible.value = true;
    };

    // 审核弹窗确认
    const handleReviewModalOk = () => {
      reviewFormRef.value.validate().then(() => {
        reviewModalLoading.value = true;
        
        axios.put(`/api/comment/${reviewFormState.id}/review?status=${reviewFormState.status}&remark=${reviewFormState.remark}`)
          .then(response => {
            if (response.data.code === 200) {
              message.success('审核成功');
              reviewModalVisible.value = false;
              fetchCommentList();
            } else {
              message.error(response.data.message || '审核失败');
            }
          })
          .catch(error => {
            console.error('审核失败:', error);
            message.error('审核失败');
          })
          .finally(() => {
            reviewModalLoading.value = false;
          });
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    // 审核弹窗取消
    const handleReviewModalCancel = () => {
      reviewModalVisible.value = false;
    };

    onMounted(() => {
      fetchCommentList();
    });

    return {
      tableLoading,
      commentList,
      pagination,
      searchForm,
      columns,
      fetchCommentList,
      handleSearch,
      resetSearch,
      handleTableChange,
      getStatusText,
      getStatusColor,
      modalVisible,
      modalLoading,
      formRef,
      formState,
      rules,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      handleDelete,
      reviewModalVisible,
      reviewModalLoading,
      reviewFormRef,
      reviewFormState,
      reviewRules,
      showReviewModal,
      handleReviewModalOk,
      handleReviewModalCancel,
    };
  }
});
</script>

<style scoped>
.comment-list {
  background-color: transparent;
}

.search-card {
  margin-bottom: 20px;
}

.comment-content-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>